<template>
  <div v-show="loaded" class="weui-panel full scroll-h" style="background: #fff">
    <div v-show="!applySuc && !isAgentAlready">
      <div class="weui-cell weui-flex">
        <div class="weui-flex__item"><label class="weui-label">邀请人ID</label></div>
        <div class="weui-flex__item_2">
          <div style="width: 70%; margin: 0 auto;">
            <input class="weui-input" v-model="upperAgentID" @keydown.enter="queryUpperAgent" 
            type="text" maxlength="6" placeholder="请输入">
          </div>
        </div>
        <div class="weui-flex__item"><a class="weui-btn weui-btn_mini weui-btn_primary" @click="queryUpperAgent">查询</a></div>
      </div>
      <div class="weui-flex" v-show="hasGetUpperAgent">
        <div class="weui-flex__item">
          <img class="list-user-img" :src="upperAgentHeadUrl" alt="">
          <div style="line-height: 36px;">{{upperAgentNickName}}</div> 
        </div>
      </div>
      <div class="weui-flex" v-show="getUpperAgentErr">
        <div class="weui-flex__item" style="text-align: center;">
          {{getUpperAgentErrMsg}}
        </div>
      </div>
      <div class="weui-cells__title">代理等级</div>
      <div class="weui-cells weui-cells_radio">
        <!-- <label class="weui-cell weui-check__label" for="x11">
          <div class="weui-cell__bd">
            <p>一级代理</p>
          </div>
          <div class="weui-cell__ft">
            <input @click="levelPromote(1)" type="radio" class="weui-check" name="radio1" id="x11">
            <span class="weui-icon-checked"></span>
          </div>
        </label> -->
        <label class="weui-cell weui-check__label" for="x12">

          <div class="weui-cell__bd">
            <p>二级代理</p>
          </div>
          <div class="weui-cell__ft">
            <input @click="levelPromote(2)" type="radio" name="radio1" class="weui-check" id="x12">
            <span class="weui-icon-checked"></span>
          </div>
        </label>
      </div>
      <div class="weui-cells__title">代理信息</div>
      <div class="weui-cells weui-cells_form">
        <div class="weui-cell" :class="{'weui-cell_warn': phoneNumberInvalid}">
          <div class="weui-cell__hd"><label class="weui-label">手机号码</label></div>
          <div class="weui-cell__bd">
            <input class="weui-input" required v-model="phoneNumber" maxlength="11"
             type="number" pattern="[0-9]*" placeholder="手机号码">
          </div>
          <div class="weui-cell__ft">
            <i class="weui-icon-warn"></i>
          </div>
        </div>
        <div class="weui-cell" :class="{'weui-cell_warn': nameInvalid}">
          <div class="weui-cell__hd">
            <label class="weui-label">姓名</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" v-model="name" type="text" maxlength="20" placeholder="姓名">
          </div>
          <div class="weui-cell__ft">
            <i class="weui-icon-warn"></i>
          </div>
        </div>
        <div class="weui-cell" :class="{'weui-cell_warn': bankNameInvalid}">
          <div class="weui-cell__hd">
            <label class="weui-label">开户银行</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" v-model="bankName" type="text" placeholder="开户银行" maxlength="60">
          </div>
          <div class="weui-cell__ft">
            <i class="weui-icon-warn"></i>
          </div>
        </div>
        <div class="weui-cell"  :class="{'weui-cell_warn': bankCardNumberInvalid}">
          <div class="weui-cell__hd">
            <label class="weui-label">银行卡号</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" v-model="bankCardNumber" type="number" pattern="[0-9]*" maxlength="30" placeholder="银行卡号">
          </div>
          <div class="weui-cell__ft">
            <i class="weui-icon-warn"></i>
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd">
            <label class="weui-label">支付宝(可选)</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" v-model="alipayAccount" type="text" maxlength="60" placeholder="支付宝">
          </div>
        </div>

        <div style="padding: 10px;">
          <a class="weui-btn weui-btn_primary" :class="{'weui-btn_disabled': !canSubmit}" @click="submit">
            <span v-show="!applying">提交</span><span v-show="applying">申请中...</span></a>
        </div>
      </div>
    </div>

    <Agent-pay v-if="applySuc && !isAgentAlready" :invite-id="upperAgentID"
     :shopping-item="shoppingItem" :proxy-level="proxyLevel" @back="applySuc = false"></Agent-pay>
    <div class="weui-msg" v-show="isAgentAlready && !showAgentDesc">
      <div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
      <div class="weui-msg__text-area">
          <h2 class="weui-msg__title">您已经是代理了</h2>
      </div>
      <div class="weui-msg__opr-area">
        <p class="weui-btn-area">
          <a @click="goDesc" class="weui-btn weui-btn_default">查看代理介绍</a>
        </p>
      </div>
      <div class="weui-msg__extra-area">
        <div class="weui-footer">
          <p class="weui-footer__text">乐翻天@2017</p>
        </div>
      </div>
    </div>
    <Agent-desc v-show="isAgentAlready && showAgentDesc"></Agent-desc>
  </div>
</template>

<script>
import 'whatwg-fetch'
import AgentPay from './AgentPay'
import AgentDesc from './AgentDesc'
export default {
  props: ['loaded', 'isAgentAlready'],
  data() {
    const token = this.getQueryString('token')
    const areaCode = this.getQueryString('areaCode')
    const config = {
      agentSystem: 'https://c-c-a.jiahuagame.com/game-lobby/',
    }
    if (window.location.hostname.match(/10.10.10/)) {
      // config.pre = 'https://10.10.10.107:8080/game-lobby'
      config.agentSystem = 'https://lefantian.jiahuagame.com/game-lobby'
    } else if (window.location.hostname.match(/lefantian/)) {
      config.agentSystem = 'https://lefantian.jiahuagame.com/game-lobby'
    } else {
      config.agentSystem = 'https://c-c-a.jiahuagame.com/game-lobby'
    }
    const api = {
      querySelf() {
        const url = `${config.agentSystem}/agent/apply/${areaCode}/inviter`;
        const opt = {
          method: 'GET',
          headers: {
            Authorization: token,
            'Content-type': 'application/json'
          }
        }
        // RESPONSE：
        // {"data":{"nickname":"abcd","headurl":"","lftid":123456,"uid":"aaaaa"},"message":"","result":0}
        return fetch(url, opt)
      },
      // URL：{path}/agent/apply/{areaCode}/{superuid}/inviter
      queryUpperAgent(send) {
        const url = `${config.agentSystem}/agent/apply/${areaCode}/${send.upperAgentID}/inviter`;
        const opt = {
          method: 'GET',
          headers: {
            Authorization: token,
            'Content-type': 'application/json'
          }
        }
        // RESPONSE：
        // {"data":{"nickname":"abcd","headurl":"","lftid":123456,"uid":"aaaaa"},"message":"","result":0}
        return fetch(url, opt)
      },
      // URL：{path}/agent/apply/{areaCode}
      apply(send) {
        const url = `${config.agentSystem}/agent/apply/${areaCode}`;
        const opt = {
          method: 'POST',
          headers: {
            Authorization: token,
            'Content-type': 'application/json'
          },
          body: JSON.stringify(send)
        }
        console.log('send', send)
        return fetch(url, opt)
      }
    }
  
    return {
      upperAgentID: '',
      upperAgentIDInvalid: false,
      phoneNumber: '',
      phoneNumberInvalid: false,
      name: '',
      nameInvalid: false,
      bankName: '',
      bankNameInvalid: false,
      bankCardNumber: '',
      bankCardNumberInvalid: false,
      alipayAccount: '',
      // 是否已经查询了上级代理ID
      hasGetUpperAgent: false,
      upperAgentNickName: '',
      upperAgentHeadUrl: '',
      upperAgentUid: '',
      getUpperAgentErr: false,
      getUpperAgentErrMsg: '',
      api,
      token,
      areaCode,
      applying: false,
      applySuc: false,
      shoppingItem: undefined,
      proxyLevel: undefined,
      showAgentDesc: false
    }
  },
  mounted() {
  },
  methods: {
    goDesc() {
      this.showAgentDesc = true
    },
    levelPromote(level) {
      console.log(level)
      const tipText = level === 1 ? '一级代理：充值500元，可得到一级代理权限和500个钻石' : '二级代理：充值200元，可得到二级代理权限和200个钻石'
      $.alert(tipText)
    },
    getQueryString(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    queryUpperAgent(goOn) {
      const pattern = /^[0-9]*$/
      if (this.upperAgentID.length !== 6 || !pattern.test(this.upperAgentID)) {
        $.alert('上级代理ID是一个6位数的数字');
      }
      const send = {
        upperAgentID: this.upperAgentID
      }
      this.hasGetUpperAgent = false
      this.upperAgentHeadUrl = ''
      this.upperAgentNickName = ''
      this.api.queryUpperAgent(send).then(res => res.json()).then(data => {
        console.log(data);
        this.getUpperAgentErr = data.result !== 0
        console.log('getUpperAgentErr', this.getUpperAgentErr);
        if (this.getUpperAgentErr) {
          this.getUpperAgentErrMsg = data.message
          return
        }
        this.hasGetUpperAgent = true
        this.upperAgentHeadUrl = data.data.headurl
        this.upperAgentNickName = data.data.nickname
        this.upperAgentUid = data.data.uid
        if (goOn) {
          this.submit()
        }
      })
    },
    submit() {
      console.log('canSubmit', this.canSubmit);
      const checkedIpt = Array.prototype.slice.call(document.getElementsByName('radio1'), 0).find(ipt => ipt.checked)
      if (!checkedIpt) {
        $.alert('请选择代理等级')
        return
      }
      this.proxyLevel = checkedIpt.id === 'x11' ? 2 : 3
      if (!this.hasGetUpperAgent) {
        this.queryUpperAgent(true)
        // $.alert('请查询邀请人, 如无可填写100000')
      }
      if (!this.canSubmit || this.applying) {
        return
      }
      const send = {
        areaCode: this.getQueryString('areaCode'),
        proxyLevel: this.proxyLevel,
        lftid: this.upperAgentID,
        auditUid: this.upperAgentUid,
        telphone: this.phoneNumber,
        realName: this.name,
        bankName: this.bankName,
        bankCard: this.bankCardNumber,
        alipayAccount: this.alipayAccount
      }
      $.confirm(`确认邀请人昵称: ${this.upperAgentNickName} `, () => {
        this.applying = true
        this.api.apply(send).then(res => res.json()).then(data => {
          console.log(data);
          this.applying = false
          // 200代表是之前支付过了 直接显示成功~
          if (data.result === 200) {
            this.$emit('agentdone')
            return
          }
          if (data.result) {
            $.alert(data.message)
            return 
          }
          this.shoppingItem = data.data[0]
          this.applySuc = true
          // $.alert('申请成功!')
        })
      })
    },
  },
  computed: {
    canSubmit() {
      this.upperAgentIDInvalid = this.upperAgentID === ''
      this.phoneNumberInvalid = this.phoneNumber === ''
      this.nameInvalid = this.name === ''
      this.bankNameInvalid = this.bankName === ''
      this.bankCardNumberInvalid = this.bankCardNumber === ''
      return !(this.upperAgentIDInvalid || this.phoneNumberInvalid ||
       this.nameInvalid || this.bankNameInvalid || this.bankCardNumberInvalid) && this.hasGetUpperAgent && !this.applying
    }
  },
  components: {
    AgentPay,
    AgentDesc
  }
}

</script>

<style lang="less">
.list-user-img {
  height: 70px; 
  width: 70px;
  border-radius: 5px;
}
.scroll-h {
  overflow-y: auto;
}
</style>